<template>
  <div class="com-full common-chart" ref="chartRef" />
</template>

<script>
export default {
  name: 'EChart'
}
</script>

<script setup>
import { onMounted, onUnmounted, ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts'
let myChart = {}

const props = defineProps(['option', 'echartClk'])
const chartRef = ref()

const destroy = () => {
  let chart = myChart[id.value]
  if (chart && chart.dispose && chart.clear) {
    chart.dispose()
    chart = null
  }
}
const init = (option) => {
  nextTick(() => {
    let chart = myChart[id.value]
    chart.clear()
    chart && chart.setOption(option)
  })
}

watch(() => props.option, (val) => {
  if (JSON.stringify(val) !== '{}') {
    init(val)
  }
}, { deep: true })

function getId () {
  let newId = Math.random() + ''
  if (myChart[newId]) {
    return getId()
  } else {
    return newId
  }
}

const id = ref(getId())

onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      destroy()
      let dom = chartRef.value
      myChart[id.value] = echarts.init(dom)

      if (props.echartClk) {
        myChart[id.value].on('click', 'series', props.echartClk)
      }
    }, 0);
  })
})

onUnmounted(() => {
  setTimeout(() => {
    destroy()
  }, 500);
})
</script>

<style lang="scss">
.common-chart {
  pointer-events: all;

  * {
    pointer-events: all;
  }
}
</style>